package com.qing.demo.util;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;


public class PDFSplitterUtils {


    public static void splitPDF( String sourceFolder, String destinationFolder){
        File folder = new File(sourceFolder);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(".pdf")) {
                    splitPDF(file, destinationFolder);
                }
            }
        }
    }

    private static void splitPDF(File file, String destinationFolder) {
        try {
            PdfReader reader = new PdfReader(file.getAbsolutePath());
            int totalPages = reader.getNumberOfPages();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String timeStamp = dateFormat.format(new Date());

            File outputFolder = new File(destinationFolder);
            if (!outputFolder.exists()) {
                outputFolder.mkdirs();
            }

            for (int i = 1; i <= totalPages; i++) {
                String outputFileName = destinationFolder + File.separator + timeStamp + "_" + i + ".pdf";
                Document document = new Document(PageSize.A4);
                PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputFileName));
                document.open();
                document.newPage();
                copy.addPage(copy.getImportedPage(reader, i));
                document.close();
                System.out.println("生成PDF文件: " + outputFileName);
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static void concatPDF(File file, String destinationFolder) {
        try {
            PdfReader reader = new PdfReader(file.getAbsolutePath());
            int totalPages = reader.getNumberOfPages();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
            String timeStamp = dateFormat.format(new Date());

            File outputFile = new File(destinationFolder + File.separator + timeStamp + ".pdf");
            Document document = new Document(PageSize.A4);

            PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputFile));
            document.open();

            for (int i = 0; i < totalPages; i++) {
                document.newPage();
                copy.addPage(copy.getImportedPage(reader, i + 1));
            }

            document.close();
            copy.close();

            System.out.println("生成单页PDF文件: " + outputFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

